package com.example.eventpush.publisher;

import com.example.eventpush.event.Level;
import com.example.eventpush.event.StudentEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhenWuWang
 */
@Component
public class StudentPublisher
{
    private ApplicationEventPublisher publisher;

    @Autowired
    public StudentPublisher(ApplicationEventPublisher publisher)
    {
        this.publisher = publisher;
    }

    public void publish() throws Exception
    {
        List<StudentEvent> studentEvents = new ArrayList<>();
        for (int i = 0; i < 100; i++)
        {
            StudentEvent studentEvent = new StudentEvent();
            studentEvent.setUserName("ruby");
            studentEvent.setScore(i * 1.0d);
            studentEvent.setLevel(i <= 50 ? Level.UN_PASS : Level.PASS);
            studentEvents.add(studentEvent);
        }
        for (StudentEvent studentEvent : studentEvents)
        {
            new Thread("thread-" + studentEvent.getScore())
            {
                @Override
                public void run()
                {
                    //            System.out.println("publish start");
                    publisher.publishEvent(studentEvent);
//            System.out.println("publish end");
                }
            }.start();
        }
    }
}
